package mymyoux.utils
{
	import flash.events.EventDispatcher;
	import flash.net.SharedObject;
	
	import mymyoux.events.CacheEvent;
	public class Cache
	{
		protected var _cache:SharedObject;
		protected var _e:EventDispatcher;
		public function Cache(name:String)
			{
				_cache=SharedObject.getLocal(name);
				_e=new EventDispatcher();

			}
			//TODO:lancer un dispatcher général
		public function setName(name:String):void{
			_cache=SharedObject.getLocal(name);
		} 
		public function setVar(name:String,value:*):void{
			if(has(name)){
				var old:*=getVar(name);
				if(old!=value){
					dispatch(name,old,value);
				}
			}else{
				dispatch(name,null,value);
			}
			_cache.data[name]=value;
			_cache.flush();
		}
		public function getVar(name:String):*{
			return _cache.data[name];
		}
		public function delVar(name:String):void{
			if(has(name)){
				dispatch(name,getVar(name),null);
			}
			delete _cache.data[name];
		}
		public function has(name:String):Boolean{
			return _cache.data[name]!=null;
		}
		public function getArray():Array{
			var a:Array;
			var i:String;
			for(i in _cache.data){
				a[i]=_cache.data[i];
			}
			return a;
		}
		public function observe(name:String,listener:Function):void{
			_e.addEventListener(CacheEvent.CHANGE+name,listener);
		}
		public function forget(name:String,listener:Function):void{
			_e.removeEventListener(CacheEvent.CHANGE+name,listener);
		}
		protected function dispatch(name:String,old:*,value:*):void{
			trace("Dispatch : "+name);
			_e.dispatchEvent(new CacheEvent(name,old,value));
		}
		//TODO:reset function

	}
}